package com.back.demo.controller;

import com.back.demo.common.CommonResult;
import com.back.demo.common.Permission;
import com.back.demo.controller.myVO.BasicVO.*;
import com.back.demo.service.BasicService;
import com.back.demo.util.JwtTokenUtil;
import com.back.demo.common.User;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

import java.util.ArrayList;

@Api(tags = "基础功能")
@RestController
@RequestMapping("/back/basic")
public class BasicController {

    @Autowired
    private BasicService basicService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @ApiOperation("验证码接口")
    @GetMapping("/get-captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 生成验证码文本
        String captchaText = defaultKaptcha.createText();

        // 将验证码文本存储在会话中，以供后续验证
        request.getSession().setAttribute("captcha", captchaText);

        // 生成验证码图片
        BufferedImage captchaImage = defaultKaptcha.createImage(captchaText);

        // 将验证码图片写入响应
        response.setContentType("image/png");
        try (OutputStream outputStream = response.getOutputStream()) {
            ImageIO.write(captchaImage, "png", outputStream);
            outputStream.flush();
        }
    }

    @ApiOperation("登录接口")
    @PostMapping("/login")
    public CommonResult<?> login(HttpServletRequest request, @RequestBody LoginReqVO reqVO) {

        String storedCaptcha = (String) request.getSession().getAttribute("captcha");
        System.out.println(storedCaptcha);
        System.out.println(reqVO.getCaptcha());
        request.getSession().removeAttribute("captcha"); // 删除会话中的验证码
        if (!reqVO.getCaptcha().equalsIgnoreCase(storedCaptcha)) { // 验证码错误，显示错误消息
            return CommonResult.error(50007, "验证码错误");
        } else { // 验证码正确，执行登录逻辑
            String username = reqVO.getUsername();

            // 查询用户
            User user = basicService.findUserByUsername(username);
            if (user == null || !reqVO.getPassword().equals(user.getPassword())) {
                return CommonResult.error(50007, "登录失败，用户名或密码不正确");
            }

            // 查询学生个人信息表

            // 生成访问令牌和刷新令牌
            String accessToken = jwtTokenUtil.generateAccessToken(username);
            String refreshToken = jwtTokenUtil.generateRefreshToken(username);
            LoginResVO resVO = new LoginResVO(accessToken, refreshToken);

            return CommonResult.success(resVO);
        }
    }

    @PostMapping("/register")
    public CommonResult<?> register(@RequestBody RegisterReqVO reqVO) {
        User user = basicService.findUserByUsername(reqVO.getUsername());

        if (user != null) {
            return CommonResult.error(50003, "用户已存在");
        }

        user = new User(reqVO.getUsername(), reqVO.getPassword());
        try {
            // 将用户信息保存到数据库
            basicService.register(user);
        } catch (Exception e) {
            // 处理插入失败的情况
            System.out.println(e.toString());
            return CommonResult.error(50003, "注册失败");
        }
        return CommonResult.success("注册成功");
    }

    @ApiOperation("获取姓名接口")
    @GetMapping("/get-name")
    public String getName(@RequestHeader("Authorization") String authHeader) {
        // 解析Authorization请求头中的JWT令牌 Bearer access_token
        String token = authHeader.substring(7);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        String name = basicService.getName(username);
        System.out.println(name);
        return name;
    }


    @GetMapping("/permission")
    public CommonResult<?> getPermission(@RequestHeader("Authorization") String authHeader) {
        // 解析Authorization请求头中的JWT令牌 Bearer access_token
        String token = authHeader.substring(7);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        ArrayList<Permission> permissionList = basicService.findPermissionByUsername(username);
        return CommonResult.success(permissionList);
    }

    /*这一块需要修改*/
    @GetMapping("/home")
    public CommonResult<?> getUserProfile(@RequestHeader("Authorization") String authHeader) {
        // 解析Authorization请求头中的JWT令牌 Bearer access_token
        String token = authHeader.substring(7);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        User user = basicService.findInformationByUsername(username);
        return CommonResult.success(user);
    }

    @PostMapping("/password")
    public CommonResult<?> changePassword(@RequestHeader("Authorization") String authHeader, @RequestBody ChangePasswordReqVO body) {
        String token = authHeader.substring(7);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        User user = basicService.findUserByUsername(username);

        if (user == null) {
            return CommonResult.error(50003, "用户不存在，修改密码失败");
        }

        if (!user.getPassword().equals(body.getOldPassword())) {
            return CommonResult.error(50003, "旧密码错误");
        }

        try {
            // 执行修改密码的操作
            basicService.changePassword(username, body.getNewPassword());
        } catch (Exception e) {
            // 处理修改失败的情况
            System.out.println(e.toString());
            return CommonResult.error(50003, "修改密码失败");
        }
        return CommonResult.success("修改密码成功");
    }


}